<?php

/**
 * Created by PhpStorm.
 * User: kc
 * Date: 2017/8/2
 * Time: 13:52
 */
class ServiceCardOrderController extends BaseController{
    /**
     * @Author:      kc
     * @DateTime:    2017-08-02 10:03:32
     * @Description: 套餐卡订单列表
     */
    public function cardOrderList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $service_card_order = ServiceCardOrder::leftJoin('service_card_base','service_card_base.id','=','service_card_order.service_card_id')
                ->select([
                    'service_card_order.order_id',
                    'service_card_order.amount',
                    'service_card_order.pay_amount',
                    'service_card_order.created_at',
                    'service_card_order.pay_type',
                    'service_card_order.status',
                    'service_card_base.name',

                ])
                ->where('service_card_order.user_id',$wechat_user->id)
                ->orderBy('service_card_order.created_at','desc')
                ->get();
            foreach($service_card_order as $v){
                $v->amount = bcdiv($v->amount,100,2);
                $v->pay_amount = bcdiv($v->pay_amount,100,2);
                $v->status_value = Orders::$service_card_status[$v->status];
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $service_card_order,
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "cardOrderList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-02 10:28:20
     * @Description: 套餐卡订单详情
     */
    public function cardOrderDetails(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $card_order = ServiceCardOrder::where('order_id',Input::get('order_id'))
                ->where('user_id',$wechat_user->id)
                ->first();
            if(!empty($card_order)){
                $card_order->status_value = Orders::$service_card_status[$card_order->status];
                $card_order->pay_type_value = isset($card_order->pay_type)?Orders::$paytype[$card_order->pay_type]:"";
                $card_order->amount = bcdiv($card_order->amount,100,2);
                $card_order->pay_amount = bcdiv($card_order->pay_amount,100,2);
                $card_order->shop_name = MaintenanceShops::where('id',$card_order->shop_id)->pluck('name');
                $pay_record = ServiceCardOrderPayRecord::where('order_id',$card_order->order_id)->where('status',1)->get();
                if(!empty($pay_record)){
                    foreach($pay_record as $v){
                        $v->amount = bcdiv($v->amount,100,2);
                    }
                }
                $card_order->pay_order_record = $pay_record;
                $card_order->service_card_base = ServiceCardBase::where('id',$card_order->service_card_id)->first();
                if(!empty($card_order->service_card_base)){
                    $card_order->service_card_base->amount = bcdiv($card_order->service_card_base->amount,100,2);
                }
                $base_pack = ServiceCardBasePack::where('service_card_base_id',$card_order->service_card_id)->get();
                if(!empty($base_pack)){
                    foreach($base_pack as $v){
                        $v->amount = bcdiv($v->amount,100,2);
                        $v->pack_name = ProductPackage::where('id',$v->pack_id)->pluck('name');
                    }
                }
                $card_order->service_card_base_puck = $base_pack;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $card_order
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "cardOrderDetails", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-02 15:34:18
     * @Description: 取消未支付套餐卡订单
     */
    public function cardOrderCancel(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            try{
                $card_order = ServiceCardOrder::find(Input::get('order_id'));
                if(!in_array($card_order->status,Orders::$to_be_confirmed)){
                    $response = Lang::get("error.service_card_order_remove_error_95008");
                    break;
                }
                $card_order->status = 1010;
                $card_order->save();

                $order_flows = new ServiceCardOrderFlow();
                $order_flows->order_id = $card_order->order_id;
                $order_flows->status = $card_order->status;
                $order_flows->user_id = $wechat_user->id;
                $order_flows->type = 'custom';
                $order_flows->save();
            }catch (Exception $e){
                Log::error("error", array("system" => "wechat2.0" ,"event" => "cardOrderCancel", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.service_card_order_remove_error_95008");
                break;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "cardOrderCancel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-02 17:16:20
     * @Description: 套餐卡详情
     */
    public function cardDetail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required'
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $card_detail = ServiceCardDetail::with(['serviceCardBase','serviceCardDetailPack'])
                ->where('user_id',$wechat_user->id)
                ->where('id',Input::get('id'))
                ->first();
            if(is_null($card_detail)){
                $response = Lang::get("error.service_card_base_error_95000");
                break;
            }
            if(!empty($card_detail->serviceCardBase)){
                $card_detail->service_card_base->amount = bcdiv($card_detail->service_card_base->amount,100,2);
                $shop_name = array();
                if($card_detail->service_card_base->limit_shop == 1){
                    $shop_name[]['name'] = MaintenanceShops::where('id',$card_detail->shop_id)->pluck('name');
                }else{
                    $service_card_base_shop = ServiceCardBaseShop::where('service_card_base_id', $card_detail->service_card_base->id)->where('status',1)->get();
                    foreach($service_card_base_shop as $v){
                        $shop_name[]['name'] = MaintenanceShops::where('id',$v->shop_id)->pluck('name');
                    }
                }
                if($card_detail->service_card_base->date_type == 1){
                    $begin_date = $card_detail->get_time;
                    $end_date = $card_detail->end_date;
                }else{
                    $begin_date = $card_detail->service_card_base->begin_date;
                    $end_date = $card_detail->service_card_base->end_date;
                }
                $card_detail->get_time = date("Y-m-d",strtotime($begin_date));
                $card_detail->end_date = date("Y-m-d",strtotime($end_date));
                $status_value = '';
                if(strtotime($end_date) < time()){
                    $status_value = '已过期';
                }

                $card_detail->status_value = $status_value;
                $scdp = ServiceCardDetailPack::where('service_card_detail_id',$card_detail->id)->where('service_card_base_id',$card_detail->service_card_base->id)->select('curr_number')->get();
                $i = 0;
                foreach($scdp as $v){
                    $i += $v->curr_number;
                }
                $card_detail->curr_number = $i;
            }
            if(!empty($card_detail->serviceCardDetailPack)){
                foreach($card_detail->service_card_detail_pack as $v){
                    $v->amount = bcdiv($v->amount,100,2);
                    $v->pack_name = ProductPackage::where('id',$v->pack_id)->pluck('name');
                    $small_icon = ProductPackage::where('id',$v->pack_id)->pluck('small_icon');
                    $v->pack_img = empty($small_icon)?"":Config::get('config.product_img').$small_icon;
                }
            }
            $card_detail->shop_name = isset($shop_name)?$shop_name:array();
            $card_detail->car = ServiceCardCar::where('user_id',$card_detail->user_id)->where('status',1)->get();
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $card_detail,
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "cardDetail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-03 11:49:40
     * @Description: 绑定车辆
     */
    public function bindCar(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $source = 0;
            $unbund_source = 0;
            if(Input::get('source')){
                $source = Input::get('source');
                $unbund_source = Input::get('unbund_source');
            }else{
                $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
                if(strpos($agent, 'iphone') || strpos($agent, 'ipad')){
                    $source = 1;
                    $unbund_source = 1;
                }
                if(strpos($agent, 'android')){
                    $source = 2;
                    $unbund_source = 2;
                }
            }

            DB::beginTransaction();
            try{
                $car_no = json_decode(Input::get('car_no'),true);
                $service_card = ServiceCard::where('user_id',$wechat_user->id)->first();
                if(empty($service_card)){
                    $service_card = new ServiceCard();
                    $service_card->account_no = date("YmdHis",time()).Common::createOrderId();
                    $service_card->user_id = $wechat_user->id;
                    $service_card->save();
                }
                ServiceCardCar::where('user_id',$wechat_user->id)->where('status',1)->where('account_no',$service_card->account_no)->update(array('status'=>0,'unbund_source'=>$unbund_source,'unbund_at'=>Common::currentTimeString(),'op_by'=>$wechat_user->id));
                foreach($car_no as $v){
                    if(empty($v['area']) || empty($v['number'])){
                        continue;
                    }
                    $service_card_car = new ServiceCardCar();
                    $service_card_car->user_id = $wechat_user->id;
                    $service_card_car->account_no = $service_card->account_no;
                    $service_card_car->car_no = $v['area'].$v['number'];
                    $service_card_car->status = 1;
                    $service_card_car->created_by = $wechat_user->id;
                    $service_card_car->source = $source;
                    $service_card_car->save();
                }
                DB::commit();
            }catch(Exception $e){
                DB::rollBack();
                Log::error("error", array("system" => "wechat2.0" ,"event" => "bindCar", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.data_save_error_30001");
                break;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "bindCar", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-08-03 11:49:40
     * @Description: 绑定车辆列表
     */
    public function bindCarList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $car = ServiceCardCar::where('user_id',$wechat_user->id)->where('status',1)->get();
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => $car
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "bindCarList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}